package rsj.service.auth;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import rsj.api.account.entity.AuthInfo;
import rsj.sql.auth.AuthInfoDao;
import rsj.util.PageQuery;
import rsj.util.PaginationData;

import java.util.List;

@Component
public class AuthServiceImpl implements IAuthService {


    @Autowired
    private AuthInfoDao authInfoDao;


    /**
     * 身份验证信息列表
     *
     * @param pageQuery  页面查询
     * @param searchName 搜索的名字
     * @return {@link PaginationData<TableNode>}
     */
    @Override
    public PaginationData<TableNode> authInfoList(PageQuery pageQuery, String searchName) {
        PaginationData<TableNode> paginationData = new PaginationData<>();
        Node node = this.countAuth(searchName);
        TableNode tableNode = authInfoDao.listByPage(pageQuery.getLimit(), pageQuery.getOffset(), searchName);
        paginationData.setTotalCount(node.valueInt());
        paginationData.setDataList(tableNode);
        return paginationData;
    }


    /**
     * 查询客户下的账号
     *
     * @param custId cust id
     * @return {@link List<AuthInfo>}
     */
    @Override
    public List<AuthInfo> authListByCustomer(String custId) {
        TableNode customer = authInfoDao.authListByCustomer(custId);
        return JSON.parseArray(customer.toJson(), AuthInfo.class);
    }

    /**
     * 获取机构的账号标识
     *
     * @param orgId 机构id
     * @return {@link String}
     */
    @Override
    public String getKeyIdByOrganization(String orgId) {
        return authInfoDao.getKeyIdByOrganization(orgId).value();
    }


    /**
     * 统计权限数
     *
     * @param searchName 搜索的条件
     * @return {@link Node}
     */
    public Node countAuth(String searchName) {
        Node count;
        if (!StringUtils.isEmpty(searchName)) {
            count = authInfoDao.countAuthLikeOrgName(searchName);
        } else {
            count = authInfoDao.countAllAuth();
        }
        return count;
    }


    /**
     * 身份验证sql
     *
     * @param orgName  搜索的条件
     * @param pageSize 页面大小
     * @param pageNow  页码
     * @return {@link String}
     */
    public String authListSql(Long pageSize, Long pageNow, String orgName) {
        String finalLikeSearch = StringUtils.isEmpty(orgName) ? "" : "WHERE org.org_sname LIKE #{%orgName%}";
        return "SELECT authon.*,org.org_name,org.org_sname,use.user_uname FROM sys.sys_authon authon "
                + " LEFT JOIN sys.sys_org org ON authon.aut_org_id = org.org_id"
                + " LEFT JOIN sys.sys_user use ON authon.aut_org_id = use.user_org_id "
                + finalLikeSearch + " ORDER BY aut_ctime DESC  "
                + " LIMIT #{pageSize} OFFSET #{pageNow}";
    }


}
